﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GetTogether.Studio.WebService;
using System.Text;
using System.Web.Services.Description;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;

public partial class WebService_Callback_Edit : GetTogether.Studio.Web.UI.PageCallback
{
    #region Attributes

    public string ProjectName
    {
        get { return Request["pn"]; }
    }
    public GetTogether.Studio.WebService.ProjectParameter Parameter
    {
        get
        {
            return GetTogether.Studio.WebService.ProjectParameter.GetSettingsByProjectName(CurrentSession.UserCode, ProjectName, CurrentSession.ShareUserCode);
        }
    }
    public string MethodName
    {
        get
        {
            return Request["mn"];
        }
    }
    public string HistoryName
    {
        get
        {
            string name = Request["history"];
            if (string.IsNullOrEmpty(name) || name.Trim().ToLower() == "undefined")
            {
                return "Recent";
            }
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, ' ');
            }
            return name;
        }
    }
    public Wsdl CurrentWsdl
    {
        get
        {
            return WebServiceHelper.GetWsdl(Parameter, GetTogether.Utility.NumberHelper.ToInt(Request["refresh"], 0) == 1);
        }
    }
    string containerDiv = "<div id='dv-method-{0}'>{1}</div>";
    string refreshMethod = "<span class='mm-split'>|</span><a class='a-btn' href='javascript:;;' onclick='ClearMethod(\"{0}\")'>Refresh</a>";

    #endregion

    private string GetViewerHtml(object ret, string fileType)
    {
        string path = string.Concat("Temp\\", CurrentSession.UserCode, "\\WebService\\", MethodName, "\\");
        string dirBase = string.Concat(AppDomain.CurrentDomain.BaseDirectory, path);
        if (!System.IO.Directory.Exists(dirBase)) System.IO.Directory.CreateDirectory(dirBase);
        fileType = string.Concat(".", fileType);
        string file = string.Concat(DateTime.Now.ToString("yyyyMMddHHmmss"));

        if (ret.GetType() == typeof(byte[]))
        {
            System.IO.File.WriteAllBytes(string.Concat(dirBase, file, fileType), (byte[])ret);
            string url = string.Concat("../", path.Replace("\\", "/"), file, fileType);
            return GetIframe(url);
        }
        else if (ret.GetType() == typeof(byte[][]))
        {
            byte[][] bs = (byte[][])ret;
            StringBuilder sbViewHtml = new StringBuilder();
            for (int i = 0; i < bs.Length; i++)
            {
                System.IO.File.WriteAllBytes(string.Concat(dirBase, file, "_", (i + 1).ToString(), fileType), (byte[])bs[i]);
                string url = string.Concat("../", path.Replace("\\", "/"), file, "_", (i + 1).ToString(), fileType);
                sbViewHtml.Append(GetIframe(url));
            }
            return sbViewHtml.ToString();
        }
        else
        {
            string url = string.Concat("../", path.Replace("\\", "/"), file, fileType);
            string content = "";
            if (ret.GetType() == typeof(string))
            {
                content = (string)ret;
                if (!string.IsNullOrEmpty(fileType))
                {
                    string fileTypeUpper = fileType.ToUpper();
                    if (fileTypeUpper == "HTML" || fileTypeUpper == "HTM") content = System.Web.HttpUtility.HtmlDecode(content);
                }
            }
            else
                content = GetTogether.Utility.SerializationHelper.SerializeToXml(ret);
            System.IO.File.WriteAllText(string.Concat(dirBase, file, fileType), content);
            return GetIframe(url);
        }
    }

    private string GetIframe(string url)
    {
        return string.Format("<div style='padding:2px;border-left:none;border-right:none;' class='box-option'><a target='_blank' href='{0}'>Open in New Window</a></div><div class=\"line-sub\"></div><iframe name=\"cmain\" width=\"100%\" height=\"350px\" marginwidth=\"0\" marginheight=\"0\" hspace=\"0\" vspace=\"0\" frameborder=\"0\" scrolling=\"yes\" style=\"background-color:#fff;\" src=\"{0}\"></iframe>", url);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            switch (type)
            {
                case 0:
                    #region Get Methods
                    WebService_Components_Methods c = (WebService_Components_Methods)Page.LoadControl("~/WebService/Components/Methods.ascx");
                    try
                    {
                        c.Methods = CurrentWsdl.Methods;
                        c.Parameter = this.Parameter;
                        c.IsProxy = GetTogether.Utility.NumberHelper.ToInt(Request["proxy"], 0) == 1;
                    }
                    catch (Exception ex)
                    {
                        c.Error = string.Concat("<textarea style='width:100%;height:500px;' roww='500' cols='50'>", ex.ToString(), "</textarea>");
                    }
                    this.Page.Controls.Add(c);
                    break;
                    #endregion
                case 1:
                    #region Get Method Information
                    GetMethodInformationMain();
                    break;
                    #endregion
                case 2:
                    #region Invoke Method
                    ResultInformation iResponse = new ResultInformation();
                    InvokeType invokeType = (InvokeType)GetTogether.Utility.NumberHelper.ToInt(Request["invoke-type"], 0);
                    object resultObject = null;
                    string retXml = string.Empty;
                    iResponse.StartTime = DateTime.Now;
                    string requestSOAP = string.Empty, responseSOAP = string.Empty;
                    System.Reflection.MethodInfo invokeMethodInfo = CurrentWsdl.GetMethodByName(MethodName);
                    MethodSetting methodSetting = new MethodSetting();
                    methodSetting.RqtMode = MethodSetting.RequestMode.Object;
                    if (GetTogether.Utility.NumberHelper.ToInt(Request["WMP_SOAP_" + MethodName], 0) == 1)
                    {
                        methodSetting.RqtMode = MethodSetting.RequestMode.SOAP;
                    }
                    try
                    {

                        methodSetting.FileType = Request["file-type"];
                        if (invokeType == InvokeType.Invoke)
                        {
                            string historyPath = GetInvokeHistoryPath();
                            if (!System.IO.Directory.Exists(historyPath)) System.IO.Directory.CreateDirectory(historyPath);
                            System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Request-Mode]"),
                                GetTogether.Utility.SerializationHelper.SerializeToXml(methodSetting));
                            if (methodSetting.RqtMode == MethodSetting.RequestMode.Object)
                            {
                                #region By Parameter
                                List<object> parameters = new List<object>();
                                StringBuilder sbParam = new StringBuilder();
                                List<object> referenceObjects = new List<object>();
                                foreach (System.Reflection.ParameterInfo pi in invokeMethodInfo.GetParameters())
                                {
                                    string rqtValue = Request.Form["WMP_" + pi.Name];
                                    sbParam.AppendLine(rqtValue);
                                    object p = WsdlHelper.ConvertParameter(CurrentWsdl, pi, rqtValue);
                                    if (pi.ParameterType.IsByRef)
                                    {
                                        referenceObjects.Add(p);
                                    }
                                    parameters.Add(p);
                                    if (!System.IO.Directory.Exists(historyPath)) System.IO.Directory.CreateDirectory(historyPath);
                                    System.IO.File.WriteAllText(GetInvokeHistoryParameterFile(pi.Name), WsdlHelper.ParameterToString(p));
                                }
                                foreach (FieldInfo fi in CurrentWsdl.GetHeaders(invokeMethodInfo))
                                {
                                    string rqtValue = Request.Form["WMP_" + fi.Name];
                                    sbParam.AppendLine(rqtValue);
                                    object p = WsdlHelper.ConvertParameter(CurrentWsdl, fi, rqtValue);
                                    if (fi.FieldType.IsByRef)
                                    {
                                        referenceObjects.Add(p);
                                    }
                                    GetTogether.Mapping.ObjectHelper.SetValue(CurrentWsdl.ServiceObject, fi.Name, p);
                                    fi.SetValue(CurrentWsdl.ServiceObject, p);
                                    //parameters.Add(p);
                                    if (!System.IO.Directory.Exists(historyPath)) System.IO.Directory.CreateDirectory(historyPath);
                                    System.IO.File.WriteAllText(GetInvokeHistoryParameterFile(fi.Name), WsdlHelper.ParameterToString(p));
                                }
                                resultObject = CurrentWsdl.Invoke(MethodName, parameters.Count > 0 ? parameters.ToArray() : null);
                                if (Parameter.AddressType == AddressType.WebService)
                                {
                                    requestSOAP = GetTogether.Web.Extension.SoapLogs.CurrentRequest;
                                    //if (!string.IsNullOrEmpty(requestSOAP)) requestSOAP = System.Web.HttpUtility.HtmlEncode(requestSOAP);
                                    responseSOAP = GetTogether.Web.Extension.SoapLogs.CurrentResponse;
                                    //if (!string.IsNullOrEmpty(responseSOAP)) responseSOAP = System.Web.HttpUtility.HtmlEncode(responseSOAP);
                                    //System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Request]"), requestSOAP);
                                    //System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Response]"), responseSOAP);
                                }
                                if (resultObject == null)
                                    retXml = "";
                                else
                                {
                                    if (Parameter.AddressType == AddressType.WebService)
                                    {
                                        retXml = GetTogether.Utility.SerializationHelper.SerializeToXml(resultObject);
                                        if (!string.IsNullOrEmpty(methodSetting.FileType))
                                        {
                                            iResponse.ViewerHtml = GetViewerHtml(resultObject, methodSetting.FileType);
                                        }
                                    }
                                    else
                                        retXml = (string)resultObject;
                                }
                                if (referenceObjects.Count > 0)
                                {
                                    retXml += "\r\n---------------------------";
                                    retXml += "\r\nBy Reference Object(s)";
                                    retXml += "\r\n---------------------------";

                                    foreach (object obj in referenceObjects)
                                    {
                                        retXml += "\r\n" + GetTogether.Utility.SerializationHelper.SerializeToXml(obj);
                                    }
                                }
                                string resultObjectXml = string.Empty;
                                if (Parameter.AddressType == AddressType.WebService)
                                    resultObjectXml = GetTogether.Utility.SerializationHelper.SerializeToXml(resultObject);
                                else
                                {
                                    resultObjectXml = retXml;
                                    if (parameters != null && parameters.Count > 0)
                                    {
                                        requestSOAP = (string)parameters[0];
                                    }
                                    responseSOAP = retXml;
                                }
                                System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Result-Object]"), resultObjectXml);
                                #endregion
                            }
                            else
                            {
                                string requestXml = Request["WMP_SOAP_Request_" + MethodName];

                                System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[SOAP-Request]"), requestXml);
                                retXml = RequestHelper.SendWebRequest(Parameter, invokeMethodInfo, requestXml);
                                System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Result-Object]"), retXml);

                                requestSOAP = requestXml;
                                responseSOAP = retXml;
                                System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Request]"), requestSOAP);
                                System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Response]"), responseSOAP);

                            }

                            if (!string.IsNullOrEmpty(requestSOAP)) requestSOAP = System.Web.HttpUtility.HtmlEncode(requestSOAP);

                            if (!string.IsNullOrEmpty(responseSOAP)) responseSOAP = System.Web.HttpUtility.HtmlEncode(responseSOAP);
                            System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Request]"), requestSOAP);
                            System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Logging-SOAP-Response]"), responseSOAP);
                            iResponse.EndTime = DateTime.Now;
                            System.IO.File.WriteAllText(GetInvokeHistoryParameterFile("[Result-Info]"), GetTogether.Utility.SerializationHelper.SerializeToXml(iResponse));
                        }
                        else
                        {
                            string historyResultFile = GetInvokeHistoryParameterFile("[Result-Info]");
                            string historyResultObjectFile = GetInvokeHistoryParameterFile("[Result-Object]");
                            if (System.IO.File.Exists(historyResultFile) && System.IO.File.Exists(historyResultObjectFile))
                            {
                                iResponse = GetTogether.Utility.SerializationHelper.FromXml<ResultInformation>(System.IO.File.ReadAllText(historyResultFile, Encoding.UTF8));
                                retXml = System.IO.File.ReadAllText(historyResultObjectFile, Encoding.UTF8);
                                //resultObject = DeserializeObject(retXml);
                                //if (!string.IsNullOrEmpty(methodSetting.FileType))
                                //{
                                //    viewerHtml = GetViewerHtml(resultObject, methodSetting.FileType);
                                //}
                            }
                            string requestSOAPFile = GetInvokeHistoryParameterFile("[Logging-SOAP-Request]");
                            string responseSOAPFile = GetInvokeHistoryParameterFile("[Logging-SOAP-Response]");
                            if (System.IO.File.Exists(requestSOAPFile)) requestSOAP = System.IO.File.ReadAllText(requestSOAPFile, Encoding.UTF8);
                            if (System.IO.File.Exists(responseSOAPFile)) responseSOAP = System.IO.File.ReadAllText(responseSOAPFile, Encoding.UTF8);
                        }
                    }
                    catch (Exception ex)
                    {
                        retXml = ex.ToString();
                    }
                    if (invokeType == InvokeType.GetHistory && string.IsNullOrEmpty(retXml))
                    {

                    }
                    else
                    {
                        #region Display
                        string forwardUrl = @"<div style='display:none;' id='dv-forward-{3}'>
<textarea style='width:500px;height:80px;margin:5px;' class='txt'>http://{0}/{1}/WebService/Edit.aspx?pn={2}&method={3}&history={4}&share-usercode={5}&share-type=0</textarea></div>";
                        string forwardHtml = string.Format(forwardUrl, string.Concat(Request.Url.Host, Request.Url.Port == 80 ? "" : (":" + Request.Url.Port.ToString())), Request.Url.AbsolutePath.Split('/')[1], System.Web.HttpUtility.UrlEncode(ProjectName), MethodName, System.Web.HttpUtility.UrlEncode(HistoryName), CurrentSession.UserCode);

                        string duration = iResponse.EndTime.Subtract(iResponse.StartTime).TotalSeconds.ToString();
                        StringBuilder sbOpenInNewWindow = new StringBuilder();
                        if (!string.IsNullOrEmpty(retXml) && string.IsNullOrEmpty(iResponse.ViewerHtml))
                        {
                            retXml = System.Web.HttpUtility.HtmlEncode(retXml);
                            sbOpenInNewWindow.Append("<span class='mm-split'>|</span>");
                            sbOpenInNewWindow.Append("Open in New Window : ");
                            string opTemp = "<a href='javascript:;;' onclick=\"ViewBy('{0}','{1}');\">{2}</a>";
                            sbOpenInNewWindow.AppendFormat(opTemp, MethodName, "viewer", "Viewer");
                            sbOpenInNewWindow.Append(" , ");
                            sbOpenInNewWindow.AppendFormat(opTemp, MethodName, "text/xml", "XML");
                            sbOpenInNewWindow.Append(" , ");
                            sbOpenInNewWindow.AppendFormat(opTemp, MethodName, "text/plain", "TEXT");
                            sbOpenInNewWindow.Append(" , ");
                            sbOpenInNewWindow.AppendFormat(opTemp, MethodName, "text/html", "HTML");
                        }

                        string info = string.Format("<div class='header-2' style='padding-left:2px;'>Duration:{0}<span class='mm-split'>|</span>Content Length:{2} {1}</div>", duration, sbOpenInNewWindow.ToString(), GetTogether.Utility.StringHelper.GetSizeString(retXml.Length.ToString()));
                        string html = string.Empty;
                        if (!string.IsNullOrEmpty(retXml) && string.IsNullOrEmpty(iResponse.ViewerHtml))
                        {
                            //retXml = System.Web.HttpUtility.HtmlEncode(retXml);
                            html = string.Format("<form id='form-{1}' method='post' target='_blank' action='../Viewer.aspx'><input name='type-{1}' id='type-{1}' type='hidden' /><textarea rows='5' name='result-{1}' style='width:100%;border-top:solid 1px #ACACAC;height:50px;'>{0}</textarea></form><div class='line-sub'></div><div id='view-as-object-{1}'></div>", retXml, MethodName);
                        }
                        else
                            html = "<div class='line-sub'></div><div class='header-2' style='padding-left:2px;'>Method was invoked successfully.</div>";
                        string invokeHtml = string.Concat(info, html, forwardHtml, iResponse.ViewerHtml);
                        WebService_Components_InvokeResult ir = Page.LoadControl("~/WebService/Components/InvokeResult.ascx") as WebService_Components_InvokeResult;
                        ir.MethodName = MethodName;
                        ir.InvokeHtml = invokeHtml;
                        ir.RequestSOAP = requestSOAP;
                        ir.ResponseSOAP = responseSOAP;
                        ir.RequestMode = methodSetting.RqtMode;
                        ir.ProjParam = Parameter;
                        ir.HistoryName = HistoryName;
                        this.Controls.Add(ir);
                        #endregion
                    }
                    break;
                    #endregion
                case 3:
                    #region Get Invoke Case
                    try
                    {
                        Dictionary<string, object> parameters = new Dictionary<string, object>();
                        System.Reflection.MethodInfo mi = CurrentWsdl.GetMethodByName(MethodName);
                        FieldInfo[] headers = CurrentWsdl.GetHeaders(mi);
                        foreach (System.Reflection.FieldInfo fi in headers)
                        {
                            string hFile = GetInvokeHistoryParameterFile(fi.Name);
                            if (System.IO.File.Exists(hFile))
                            {
                                string hValue = System.IO.File.ReadAllText(hFile, System.Text.Encoding.UTF8);
                                parameters.Add(fi.Name, WsdlHelper.ConvertParameter(CurrentWsdl, fi, hValue));
                            }
                        }
                        foreach (System.Reflection.ParameterInfo pi in mi.GetParameters())
                        {
                            string hFile = GetInvokeHistoryParameterFile(pi.Name);
                            if (System.IO.File.Exists(hFile))
                            {
                                string hValue = System.IO.File.ReadAllText(hFile, System.Text.Encoding.UTF8);
                                parameters.Add(pi.Name, WsdlHelper.ConvertParameter(CurrentWsdl, pi, hValue));
                            }
                        }

                        if (mi.GetParameters().Length != parameters.Count - headers.Length)
                            GetMethodInformationMain();
                        else
                            Response.Write(GetMethodInformation(MethodName, parameters, mi.ReturnType, GetMethodSetting()));
                    }
                    catch (Exception ex)
                    {
                        string exError = string.Format("<textarea rows='5' style='width:100%;height:100px;'>{0}</textarea>", ex.ToString());
                        string header = string.Format("<div class='header-2' style='padding-left:2px;'>{0}{1}</div><div class='line-sub'></div>", MethodName, string.Format(refreshMethod, MethodName, Parameter.Address));
                        Response.Write(string.Format(containerDiv, MethodName, header + exError));
                    }
                    break;
                    #endregion
                case 4:
                    #region Delete Invoke Case
                    try
                    {
                        string path = GetInvokeHistoryPath();
                        if (System.IO.Directory.Exists(path))
                        {
                            string pathDeleted = System.IO.Path.Combine(GetTogether.Studio.WebService.ProjectParameter.GetSettingsPath(CurrentSession.UserCode), "Deleted Invoke Case\\" + MethodName + "\\" + HistoryName);
                            if (!System.IO.Directory.Exists(pathDeleted))
                                System.IO.Directory.CreateDirectory(pathDeleted);
                            GetTogether.Utility.DirectoryHelper.CopyParameter cp = new GetTogether.Utility.DirectoryHelper.CopyParameter();
                            cp.Destination = pathDeleted;
                            cp.Source = path;
                            cp.IsOverwrite = true;
                            GetTogether.Utility.DirectoryHelper.Copy(cp);
                            System.IO.Directory.Delete(path, true);
                        }
                        JsonSuccess();
                    }
                    catch (Exception ex)
                    {
                        JsonError(ex.ToString());
                    }
                    break;
                    #endregion
                case 5:
                    #region Get Web Proxy Case
                    WebService_Components_ProxyCase cProxyCase = Page.LoadControl("~/WebService/Components/ProxyCase.ascx") as WebService_Components_ProxyCase;
                    cProxyCase.Parameter = Parameter;
                    cProxyCase.MethodName = MethodName;
                    this.Page.Controls.Add(cProxyCase);
                    break;
                    #endregion
                case 6:
                    #region Proxy Edit
                    string actionType = Request["ActionType"];
                    WebServiceProxyHelper.ProxyType proxyType = (WebServiceProxyHelper.ProxyType)GetTogether.Utility.NumberHelper.ToInt(Request["ProxyType"], 0);
                    string proxyName = Request.Form["ProxyName"];
                    string proxyRegular = Request.Form["ProxyRegular"];
                    string proxyRequest = Request.Form["ProxyRequest"];
                    string proxyResponse = Request.Form["ProxyResponse"];
                    string error = string.Empty;
                    if (!string.IsNullOrEmpty(proxyName))
                    {
                        proxyName = System.Web.HttpUtility.UrlDecode(proxyName);
                        if (proxyType == WebServiceProxyHelper.ProxyType.Case)
                        {
                            proxyName = proxyName.Trim().Replace(" ", "_").Replace("*", "_").
                                Replace("/", "_").Replace("!", "_").Replace("~", "_").Replace("@", "_").Replace("#", "_").
                                Replace("$", "_").Replace("%", "_").Replace("^", "_").Replace("&", "_").Replace("*", "_").
                                Replace("(", "_").Replace(")", "_").Replace("+", "_").Replace("<", "_").Replace(">", "_").Replace("?", "_");
                        }
                    }
                    if (actionType == "SAVE" || actionType == "ADD")
                    {
                        if (string.IsNullOrEmpty(proxyName)) proxyName = HistoryName;
                        if (string.IsNullOrEmpty(proxyName)) proxyName = "Recent";
                        if (string.IsNullOrEmpty(proxyName) || string.IsNullOrEmpty(proxyRequest) || string.IsNullOrEmpty(proxyResponse))
                        {
                            error = "Invalid Parameter";
                        }
                        else
                        {
                            proxyRequest = System.Web.HttpUtility.UrlDecode(proxyRequest);
                            proxyResponse = System.Web.HttpUtility.UrlDecode(proxyResponse);

                            if (proxyType == 0)
                            {
                                GetTogether.Web.CacheHelper.SetCache(proxyName, proxyResponse);
                            }
                            else
                            {
                                error = WebServiceProxyHelper.SaveProxy(CurrentSession.UserCode, ProjectName, MethodName, proxyName, Request.Form["ProxyRegular"], proxyRequest, proxyResponse);
                            }

                        }
                    }
                    else if (actionType == "DEL")
                    {
                        error = DeleteProxy(proxyType, proxyName);
                    }
                    Response.Write(string.IsNullOrEmpty(error) ? "OK" : error);
                    break;
                    #endregion
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    public string DeleteProxy(WebServiceProxyHelper.ProxyType proxyType, string proxyName)
    {
        try
        {
            if (proxyType == WebServiceProxyHelper.ProxyType.Cache)
            {
                string proxyKey = proxyName;
                if (!string.IsNullOrEmpty(proxyKey))
                {
                    proxyKey = System.Web.HttpUtility.UrlDecode(proxyKey);
                    GetTogether.Web.CacheHelper.RemoveCache(proxyKey);
                }
                else
                {
                    string prefixCacheKey = string.Concat("Proxy", "|", CurrentSession.UserCode, "|", Parameter.ProjectName, "|", MethodName, "|");
                    System.Web.Caching.Cache _cache = HttpRuntime.Cache;
                    IDictionaryEnumerator cacheEnum = _cache.GetEnumerator();
                    Dictionary<string, List<string>> ret = new Dictionary<string, List<string>>();
                    while (cacheEnum.MoveNext())
                    {
                        string key = cacheEnum.Key.ToString();
                        if (key.StartsWith(prefixCacheKey))
                        {
                            GetTogether.Web.CacheHelper.RemoveCache(key);
                        }
                    }
                }
            }
            else
            {
                string proxyPath = WebServiceProxyHelper.GetProxyPath(CurrentSession.UserCode, ProjectName, MethodName);
                proxyPath = System.IO.Path.Combine(proxyPath, proxyName);
                System.IO.Directory.Delete(proxyPath, true);
            }
            return string.Empty;
        }
        catch (Exception ex)
        {
            GetTogether.Studio.Log.Error(ex);
            return ex.ToString();
        }
    }
    private string GetMethodInformation(string methodName, Dictionary<string, object> parameters, Type returnType, MethodSetting methodSetting)
    {
        string buttons = string.Format(@"
<div class='' style='clear:both;'>
<table cellspacing='0px' cellpadding='0px' style='width:100%;'><tr>
<td style='width:5%;white-space:nowrap;'>Case Name</td><td class='tdpbl tdpbr'>
<input type='text' maxlength='50' style='width:100%;height:17px;' id='invoke-history-{0}' class='txt-2' value='{1}' /></td>
<td style='width:5%;white-space:nowrap;'>File Type</td><td class='tdpbl'>
<input type='text' maxlength='50' style='width:100%;height:17px;' id='file-type-{0}' class='txt-2' value='{2}' /></td>
</tr>
<tr><td colspan='4' class='line-wsp'></td></tr>
<tr><td colspan='4' style='padding:2px;text-align:center;'>
<input type='button' id='invoke-{0}' class='btn' 
value='Invoke' onclick='InvokeWebMethod(""{0}"")' />
<input type='button' value='Share' class='btn' style='display:none;' onclick='ShareInvoke(""{0}"");' id='btn-forward-{0}' />
</td></tr>
</table>



</div>", MethodName, HistoryName, methodSetting.FileType);
        try
        {
            System.Reflection.MethodInfo mi = CurrentWsdl.GetMethodByName(MethodName);
            StringBuilder sbParameter = new StringBuilder();
            StringBuilder sbMethod = new StringBuilder();
            StringBuilder sbHtml = new StringBuilder();
            #region Method Parameters
            FieldInfo[] headers = CurrentWsdl.GetHeaders(mi);
            foreach (string pName in parameters.Keys)
            {
                bool isHeader = false;
                foreach (FieldInfo fi in headers)
                {
                    if (pName == fi.Name)
                    {
                        isHeader = true; break;
                    }
                }
                object p = parameters[pName];
                Type pType = p.GetType();
                bool isSystemParam = WsdlHelper.IsSystemType(pType);
                string paramName = pType.Name;
                string paramColor = isSystemParam ? "blue" : "#2B91AF";
                string defaultValue = string.Empty;
                string styleWidth = (isSystemParam || pType.IsEnum) ? "width:100%;" : "width:100%;";
                defaultValue = WsdlHelper.ParameterToString(p);
                int styleHeight = 17;
                if (isSystemParam || pType.IsEnum)
                {
                    styleHeight = 17;
                }
                else
                {
                    styleHeight = GetRowsHeight(defaultValue);
                }
                if (Parameter.AddressType == AddressType.Normal)
                {
                    string[] defaultValueRows = defaultValue.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    if (parameters.Count == 1)
                        styleHeight = 300;
                    else if (pName == "requestContent")
                        styleHeight = 250;
                    else if (pName == "properties")
                        styleHeight = 100;
                }
                string enumInfo = WsdlHelper.GetEnumInfo(pType);
                if (styleHeight > 17)
                {
                    string pNameParameter = pName;
                    pNameParameter = string.Concat("<div style='padding-top:2px;'>", pNameParameter, "</div>");
                    sbParameter.AppendFormat("<tr><td style='width:5%;white-space:nowrap;vertical-align:top;'>{0}<div class='comment-box' style='margin-top:5px;'><span style='padding-left:0px;color:{1}'>{2}</span></div> {3}", pName, paramColor, pType.Name, "");
                }
                else
                    sbParameter.AppendFormat("<tr><td style='width:5%;white-space:nowrap;vertical-align:top;'><span style='padding-left:0px;color:{1}'>{2}</span> {0} {3}", pName, paramColor, pType.Name, "");
                if (isHeader)
                {
                    sbParameter.AppendFormat("<div class='comment-box' style='margin-top:5px;'>{0}</div>", "Soap Header Attribute");
                }
                string textClassName = "txt-2";
                if (Parameter.AddressType == AddressType.Normal && pName == "requestContent") textClassName = "txt-bottom";
                sbParameter.AppendFormat("</td><td><textarea class='{4}' rows='5' id='WMP_{0}' style='height:{1}px;{3}'>{2}</textarea></td></tr>", pName, styleHeight, defaultValue, styleWidth, textClassName);
                if (!string.IsNullOrEmpty(enumInfo))
                {
                    sbParameter.Append("<tr><td></td><td class='line-sub'></td></tr>");
                    sbParameter.AppendFormat("<tr><td></td><td><div class='comment-box'>{0}</div></td></tr>", enumInfo);
                }
                //if (isHeader)
                //{
                //    sbParameter.AppendFormat("<tr><td></td><td><div class='comment-box'>{0}</div></td></tr>", "Header");
                //}
                if (!pType.IsEnum)
                {
                    Dictionary<string, Type> dicEnumType = GetTogether.Studio.WebService.WsdlHelper.GetEnumTypeList(CurrentWsdl, pType, null);
                    foreach (string k in dicEnumType.Keys)
                    {
                        sbParameter.Append("<tr><td></td><td class='line-sub'></td></tr>");
                        sbParameter.AppendFormat("<tr><td></td><td><div class='comment-box'>{0} : {1}</div></td></tr>", k, WsdlHelper.GetEnumInfo(dicEnumType[k]));
                    }
                }
                if (Parameter.AddressType == AddressType.Normal && pName == "requestContent")
                {
                    sbParameter.AppendFormat(@"<tr><td></td><td><div class='comment-box'><a href='javascript:;;' onclick='FormatXml(""WMP_{0}"");' >Format XML</a></div></tr>", pName);
                }
                sbParameter.Append("<tr><td colspan='2' class='line-wsp'></td></tr>");
                if (sbMethod.Length > 0) sbMethod.Append(",");
                if (!isHeader)
                    sbMethod.AppendFormat("<span style='color:{1};'>{0}</span>", paramName, paramColor).Append(" ").Append(pName);
            }
            sbMethod.Insert(0, "(");
            sbMethod.Insert(0, string.Format("<strong>{0}</strong>", MethodName));
            sbMethod.Append(")");
            if (CurrentSession.IsFromSchedule)
            {
                sbMethod = new StringBuilder();
                sbMethod.Append(methodName);
            }
            sbMethod.AppendFormat(refreshMethod, methodName, Parameter.Address);
            if (Parameter.AddressType == AddressType.WebService)
            {
                sbMethod.AppendFormat(@"<span class='mm-split'>|</span><span class='a-btn'><input type='radio' id='WMP_Object_{0}' {1} value='{2}' name='request-mode-{0}' onclick='ChangeRequestMode(""{0}"",""object"");' />&nbsp;<label for='WMP_Object_{0}'>Parameter</label></span>", methodName, methodSetting.RqtMode == MethodSetting.RequestMode.Object ? "checked='checked'" : "", methodSetting.RqtMode == MethodSetting.RequestMode.Object ? "1" : "");

                sbMethod.AppendFormat(@"<span class='mm-split'>|</span><span class='a-btn'><input type='radio' id='WMP_SOAP_{0}' {1} value='{2}' name='request-mode-{0}' onclick='ChangeRequestMode(""{0}"",""soap"");' />&nbsp;<label for='WMP_SOAP_{0}'>Web Request</label></span>", methodName, methodSetting.RqtMode == MethodSetting.RequestMode.SOAP ? "checked='checked'" : "", methodSetting.RqtMode == MethodSetting.RequestMode.Object ? "0" : "1");
            }
            sbHtml.Append(string.Format("<div class='header-2' style='padding-left:2px;line-height:1.5em;'>{0}</div>", sbMethod.ToString()));
            string objParamStyle = methodSetting.RqtMode == MethodSetting.RequestMode.SOAP ? "display:none;" : "";
            string soapStyle = methodSetting.RqtMode == MethodSetting.RequestMode.Object ? "display:none;" : "";
            if (sbParameter.Length > 0)
            {
                sbParameter.Insert(0, string.Format("<div class='web-service-parameter' id='dv-parameter-{0}' style='{1}'><div class='line-wsp'></div><table style='width:100%;' cellpadding='0px' cellspacing='0px'>", methodName, objParamStyle));
                sbParameter.Append("</table></div>");
                sbHtml.Append(sbParameter.ToString());
            }
            else
            {
                sbHtml.Append("<div class='line-sub'></div>");
            }
            if (Parameter.AddressType == AddressType.WebService)
            {
                sbHtml.AppendFormat(@"<div id='dv-parameter-soap-{0}' class='web-service-parameter' style='{1}'><div class='line-wsp'></div><table style='width:100%;' cellpadding='0px' cellspacing='0px'><tr><td style='width:5%;white-space:nowrap;vertical-align:top;'>Web Request<div class='header-2'></div>", methodName, soapStyle);

                string soapRequestXml = string.Empty;
                string soapRequestXmlPath = GetInvokeHistoryParameterFile("[SOAP-Request]");
                if (System.IO.File.Exists(soapRequestXmlPath)) soapRequestXml = System.IO.File.ReadAllText(soapRequestXmlPath, System.Text.Encoding.UTF8);
                sbHtml.AppendFormat(@"</td><td><textarea class='txt-bottom' rows='5' id='WMP_SOAP_Request_{0}' 
style='height:300px;width:100%;'>{1}</textarea></td></tr><tr><td></td><td><div class='comment-box'><a href='javascript:;;' onclick='FormatXml(""WMP_SOAP_Request_{0}"");' >Format XML</a></div></td></tr></table></div>", methodName, soapRequestXml);
            }
            #endregion
            #region Return Type
            StringBuilder sbReturn = new StringBuilder();
            sbReturn.Append("<table style='width:100%;' cellpadding='0px' cellspacing='0px'>");

            object returnObject = null;
            if (mi.ReturnType.Name != "Void" && System.Type.GetTypeCode(returnType) == TypeCode.Object)
                returnObject = CurrentWsdl.GetObject(mi.ReturnType);
            string returnObjectXml = GetTogether.Utility.SerializationHelper.SerializeToXml(returnObject);
            string returnColor = !WsdlHelper.IsSystemType(returnType) ? "#2B91AF" : "blue";
            string returnTypeId = returnType.Name.Replace("[]", "").Replace("&", "");
            sbReturn.AppendFormat(@"<tr><td style='width:5%;white-space:nowrap;padding:0px 2px;line-height:1.5em;'>
Return <span style='color:{0};font-weight:bold;'>{1}</span></td><td>
<form id='form-{2}-{4}' method='post' target='_blank' action='../Viewer.aspx'>
<input name='type-{2}-{4}' id='type-{2}-{4}' type='hidden' />
<textarea class='txt-2' rows='5' id='result-{2}-{4}' name='result-{2}-{4}' style='display:none;width:100%;height:19px;'>{3}</textarea></form>",
returnColor, returnType.Name, methodName, returnObjectXml, returnTypeId);
            Dictionary<string, Type> dicEnumTypeReturn = null;
            if (!returnType.IsEnum)
            {
                dicEnumTypeReturn = GetTogether.Studio.WebService.WsdlHelper.GetEnumTypeList(CurrentWsdl, returnType, null);
            }
            if (returnObject != null || returnType.IsEnum)
            {
                if (!returnType.IsEnum)
                {
                    string opTemp = "<a href='javascript:;;' onclick=\"$('#type-{0}-{1}').val('{2}');$('#form-{0}-{1}')[0].submit();\">{3}</a>";
                    sbReturn.Append("View Object : ");
                    sbReturn.AppendFormat(opTemp, MethodName, returnTypeId, "viewer", "Viewer");
                    sbReturn.Append("&nbsp;,&nbsp;");
                    sbReturn.AppendFormat(opTemp, MethodName, returnTypeId, "text/xml", "XML");
                    sbReturn.Append("&nbsp;,&nbsp;");
                    sbReturn.AppendFormat(opTemp, MethodName, returnTypeId, "text/plain", "Text");
                    sbReturn.Append("&nbsp;,&nbsp;");
                    sbReturn.AppendFormat(opTemp, MethodName, returnTypeId, "text/html", "HTML");
                }
                if (returnType.IsEnum || (dicEnumTypeReturn != null && dicEnumTypeReturn.Count > 0))
                    sbReturn.AppendFormat("<span class='mm-split'>|</span>Enum Information : <a id='atest' href='javascript:;;' method-name='{0}' onclick='ShowReturnInfo(this);'>View</a>", methodName);

            }
            sbReturn.Append("</td></tr>");
            if (!returnType.IsEnum)
            {
                foreach (string k in dicEnumTypeReturn.Keys)
                {
                    sbReturn.AppendFormat("<tr class='return-info-{2}' style='display:none;'><td></td><td class='line-sub'><div class='comment-box'>{0} : {1}</div></td></tr>", k, WsdlHelper.GetEnumInfo(dicEnumTypeReturn[k]), methodName);
                }
            }
            else
            {
                sbReturn.AppendFormat("<tr class='return-info-{1}' style='display:none;'><td></td><td><div class='comment-box'>{0}</div></td></tr>", WsdlHelper.GetEnumInfo(returnType), methodName);
            }
            sbReturn.Append("<tr><td colspan='2' class='line-wsp'></td></tr>");
            sbReturn.Append("</table>");
            sbHtml.Append(sbReturn.ToString());


            #endregion
            sbHtml.Append(GetInvokeHistory());
            sbHtml.Append(buttons);
            return string.Format(containerDiv, MethodName, sbHtml.ToString());
        }
        catch (Exception ex)
        {
            string exError = string.Format("<textarea rows='5' style='width:100%;height:100px;'>{0}</textarea>", ex.ToString());
            string header = string.Format("<div class='header-2' style='padding-left:2px;'>{0}{1}</div><div class='line-sub'></div>", MethodName, string.Format(refreshMethod, methodName, Parameter.Address));
            return string.Format(containerDiv, MethodName, header + exError);
        }
    }
    private int GetRowsHeight(string v)
    {
        int styleHeight = 0;
        string[] defaultValueRows = v.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
        styleHeight = 17 * defaultValueRows.Length + 17;
        return styleHeight;
    }
    private void GetMethodInformationMain()
    {
        try
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            System.Reflection.MethodInfo mi = CurrentWsdl.GetMethodByName(MethodName);
            foreach (FieldInfo fi in CurrentWsdl.GetHeaders(mi))
            {
                object objDefault = WsdlHelper.GetParameterDefaultValue(CurrentWsdl, fi.FieldType);
                parameters.Add(fi.Name, objDefault);
            }
            foreach (System.Reflection.ParameterInfo pi in mi.GetParameters())
            {
                object objDefault = WsdlHelper.GetParameterDefaultValue(CurrentWsdl, pi.ParameterType);
                parameters.Add(pi.Name, objDefault);
            }
            Response.Write(GetMethodInformation(MethodName, parameters, mi.ReturnType, GetMethodSetting()));
        }
        catch (Exception ex)
        {
            string exError = string.Format("<textarea rows='5' style='width:100%;height:100px;'>{0}</textarea>", ex.ToString());
            string header = string.Format("<div class='header-2' style='padding-left:2px;'>{0}{1}</div><div class='line-sub'></div>", MethodName, string.Format(refreshMethod, MethodName, Parameter.Address));
            Response.Write(string.Format(containerDiv, MethodName, header + exError));
        }
    }

    private string GetInvokeHistoryPath()
    {
        string path = GetTogether.Studio.WebService.ProjectParameter.GetSettingsPath(CurrentSession.UserCode);
        path = System.IO.Path.Combine(path, string.Concat(ProjectName, "(History)\\", MethodName));
        string htyName = HistoryName;
        if (string.IsNullOrEmpty(htyName)) htyName = "Recent";
        path = System.IO.Path.Combine(path, htyName);
        return path;
    }

    private string GetInvokeHistoryParameterFile(string pName)
    {
        return System.IO.Path.Combine(GetInvokeHistoryPath(), string.Concat(pName, ".txt"));
    }

    private string GetInvokeHistory()
    {
        string invokeHistory = string.Empty;
        WebService_Components_InvokeHistory c = (WebService_Components_InvokeHistory)Page.LoadControl("~/WebService/Components/InvokeHistory.ascx");
        c.Parameter = this.Parameter;
        c.MethodName = MethodName;
        invokeHistory = c.Html;
        return invokeHistory;
    }

    private MethodSetting GetMethodSetting()
    {
        string requestMethodFile = GetInvokeHistoryParameterFile("[Request-Mode]");
        MethodSetting methodSetting = null;
        if (System.IO.File.Exists(requestMethodFile))
        {
            methodSetting = GetTogether.Utility.SerializationHelper.FromXml<MethodSetting>(System.IO.File.ReadAllText(requestMethodFile, System.Text.Encoding.UTF8));
        }
        if (methodSetting == null)
        {
            methodSetting = new MethodSetting();
            methodSetting.RqtMode = MethodSetting.RequestMode.Object;
        }
        return methodSetting;
    }
}
